package com.lcx.core.exector;

import com.lcx.core.HandleCore;
import com.lcx.listener.WebReloadListener;
import com.lcx.thread.impl.TaskMission;
import com.lcx.util.JsTemplateUtil;
import javafx.scene.web.WebEngine;

public class Exector {

    private WebEngine webEngine;

    private SyncExector exector;

    private TaskMission taskMission;

    public Exector(WebEngine webEngine, SyncExector exector){
        this.webEngine = webEngine;
        this.exector = exector;
        taskMission = new TaskMission();
    }

    /**
     * 异步执行js中指定的java对象方法
     * @param id 类名ID
     * @param name 方法名
     * @param args 方法参数
     * @param compId 完成回掉
     * @return
     */
    public void exec(String id,String name,String args,String compId){
        taskMission.addMission(new TaskMission.MissionQueue(){
            @Override
            protected Object process() throws Exception{
                return exector.exec(id,name,args);
            }

            @Override
            protected void postTodo(Object obj) {
                JsTemplateUtil.execCompleteFunc(webEngine,compId,1,obj);
            }

            @Override
            protected void errAction(String msg) {
                JsTemplateUtil.execCompleteFunc(webEngine,compId,0,msg);
            }

            @Override
            protected void stopMission() {
                WebReloadListener webReloadListener = (WebReloadListener) HandleCore.getWebReloadListenerObject(id);
                if(webReloadListener!=null){
                    webReloadListener.stopCurrent();
                }
            }
        });
        taskMission.start();
    }

    public void destoryTaskMission(){
        TaskMission taskMission = this.taskMission;
        this.taskMission = null;
        if(taskMission!=null){
            taskMission.destory();
        }
    }

    public void stopAllMission(){
        TaskMission taskMission = this.taskMission;
        if(taskMission!=null){
            taskMission.stopAndClear();
        }
    }
}
